#include <vector>
using std::vector;

//旋转数组总有一部分有序，筛选有序部分进行查找
class Solution {
public:
    int search(vector<int>& nums, int target) {
        int size = nums.size();
        if (size == 1) {
            if (nums[0] == target)
                return 0;
            else 
                return -1;
        } else {
            int left = 0;
            int right = size - 1;
            while (left <= right) {
                int mid = left + (right - left) / 2;
                if (nums[mid] == target)
                    return mid;
                else {
                    if (nums[left] <= nums[mid]) {
                        if (nums[left] <= target && nums[mid] > target)
                            right = mid - 1;
                        else 
                            left = mid + 1;
                    } else {
                        if (nums[right] >= target && nums[mid] < target)
                            left = mid + 1;
                        else
                            right = mid - 1;
                    }
                }
            }
            return -1;
        }
    }
};

//若存在重复元素，预先判断
class Solution {
public:
    bool search(vector<int>& nums, int target) {
        int size = nums.size();
        if (size == 1) {
            if (nums[0] == target)
                return true;
            else 
                return false;
        } else {
            int left = 0;
            int right = size - 1;
            while (left <= right) {
                int mid = left + (right - left) / 2;
                if (nums[mid] == target)
                    return true;
                else {
                    if (nums[left] == nums[mid])
                        left = left + 1;
                    else if (nums[right] == nums[mid])
                        right = right - 1;
                    else if (nums[left] < nums[mid]) {
                        if (nums[left] <= target && nums[mid] > target)
                            right = mid - 1;
                        else 
                            left = mid + 1;
                    } else {
                        if (nums[right] >= target && nums[mid] < target)
                            left = mid + 1;
                        else
                            right = mid - 1;
                    }
                }
            }
            return false;
        }
    }
};
